package leetcode.top100;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2022/12/16 8:21 PM
 * @description：
 */
public class _049_字母异位词分组 {
    @Test
    public void test() {

    }

    /*class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            Map<String, List<String>> map = new HashMap<>();
            for (String str : strs) {
                char[] chars = str.toCharArray();
                Arrays.sort(chars);
                String sortStr = new String(chars);
                List<String> list = map.getOrDefault(sortStr, new ArrayList<>());
                list.add(str);
                map.put(sortStr, list);
            }

            return new ArrayList<>(map.values());
        }
    }*/

    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            Map<String, List<String >> map = new HashMap<>();
            for (String str : strs) {
                int[] count = new int[26];
                char[] chars = str.toCharArray();
                for (char ch : chars) {
                    count[ch - 'a']++;
                }
                StringBuilder builder = new StringBuilder(26);
                for (int i = 0; i < 26; i++) {
                    if (count[i] != 0) {
                        builder.append((char)('a' + i));
                        builder.append(count[i]);
                    }
                }
                List<String> list = map.getOrDefault(builder.toString(), new ArrayList<>());
                list.add(str);
                map.put(builder.toString(), list);
            }
            List<List<String>> ans = new ArrayList<>();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                ans.add(entry.getValue());
            }
            return new ArrayList<>(map.values());
        }
    }
}
